import 'dart:convert';
import 'dart:developer';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';

import '../../../core/base/base_service.dart';
import '../../../core/errors/exceptions.dart';

/// 安全存储服务 - 用于存储敏感信息（如令牌、密码等）
class SecureStorageService extends BaseService {
  /// Flutter安全存储实例
  final FlutterSecureStorage _storage = const FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ),
  );
  
  /// 读取字符串类型的数据
  Future<String?> read(String key) async {
    try {
      return await _storage.read(key: key);
    } catch (e) {
      logError('读取安全存储失败', e);
      throw CacheException(
        message: '读取安全存储失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 写入字符串类型的数据
  Future<void> write(String key, String value) async {
    try {
      await _storage.write(key: key, value: value);
    } catch (e) {
      logError('写入安全存储失败', e);
      throw CacheException(
        message: '写入安全存储失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 删除指定键的数据
  Future<void> delete(String key) async {
    try {
      await _storage.delete(key: key);
    } catch (e) {
      logError('删除安全存储失败', e);
      throw CacheException(
        message: '删除安全存储失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 清除所有数据
  Future<void> deleteAll() async {
    try {
      await _storage.deleteAll();
    } catch (e) {
      logError('清除安全存储失败', e);
      throw CacheException(
        message: '清除安全存储失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 检查是否存在指定键的数据
  Future<bool> containsKey(String key) async {
    try {
      return (await _storage.read(key: key)) != null;
    } catch (e) {
      logError('检查安全存储键失败', e);
      return false;
    }
  }
  
  /// 读取JSON数据并转换为Map
  Future<Map<String, dynamic>?> readMap(String key) async {
    try {
      final data = await read(key);
      if (data == null || data.isEmpty) {
        return null;
      }
      
      return json.decode(data) as Map<String, dynamic>;
    } catch (e) {
      logError('读取安全存储Map失败', e);
      return null;
    }
  }
  
  /// 将Map转换为JSON并写入
  Future<void> writeMap(String key, Map<String, dynamic> value) async {
    try {
      final data = json.encode(value);
      await write(key, data);
    } catch (e) {
      logError('写入安全存储Map失败', e);
      throw CacheException(
        message: '写入安全存储Map失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 读取布尔类型的数据
  Future<bool> readBool(String key) async {
    try {
      final value = await read(key);
      return value == 'true';
    } catch (e) {
      logError('读取安全存储Bool失败', e);
      return false;
    }
  }
  
  /// 写入布尔类型的数据
  Future<void> writeBool(String key, bool value) async {
    try {
      await write(key, value.toString());
    } catch (e) {
      logError('写入安全存储Bool失败', e);
      throw CacheException(
        message: '写入安全存储Bool失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 读取整数类型的数据
  Future<int?> readInt(String key) async {
    try {
      final value = await read(key);
      if (value == null || value.isEmpty) {
        return null;
      }
      
      return int.parse(value);
    } catch (e) {
      logError('读取安全存储Int失败', e);
      return null;
    }
  }
  
  /// 写入整数类型的数据
  Future<void> writeInt(String key, int value) async {
    try {
      await write(key, value.toString());
    } catch (e) {
      logError('写入安全存储Int失败', e);
      throw CacheException(
        message: '写入安全存储Int失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 读取双精度浮点数类型的数据
  Future<double?> readDouble(String key) async {
    try {
      final value = await read(key);
      if (value == null || value.isEmpty) {
        return null;
      }
      
      return double.parse(value);
    } catch (e) {
      logError('读取安全存储Double失败', e);
      return null;
    }
  }
  
  /// 写入双精度浮点数类型的数据
  Future<void> writeDouble(String key, double value) async {
    try {
      await write(key, value.toString());
    } catch (e) {
      logError('写入安全存储Double失败', e);
      throw CacheException(
        message: '写入安全存储Double失败：$e',
        statusCode: 0,
      );
    }
  }
  
  /// 存储访问令牌
  Future<void> saveAccessToken(String token) async {
    await write('access_token', token);
  }
  
  /// 存储刷新令牌
  Future<void> saveRefreshToken(String token) async {
    await write('refresh_token', token);
  }
  
  /// 存储令牌过期时间
  Future<void> saveTokenExpiry(DateTime expiry) async {
    await write('token_expiry', expiry.toIso8601String());
  }
  
  /// 获取令牌过期时间
  Future<DateTime?> getTokenExpiry() async {
    final expiryStr = await read('token_expiry');
    if (expiryStr == null || expiryStr.isEmpty) {
      return null;
    }
    
    try {
      return DateTime.parse(expiryStr);
    } catch (e) {
      return null;
    }
  }
  
  /// 清除所有认证信息
  Future<void> clearAuthData() async {
    await delete('access_token');
    await delete('refresh_token');
    await delete('token_expiry');
    await delete('user_info');
  }
} 